﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.Util;

namespace WinFormsApp1.utils;



public class TestClass
{
    
	/**
	 * 根据文件夹路径和文件名读取excel文件
	 */
	public void readExcel(string folderPath, string fileName)
	{
		folderPath = @"E:\work_install\riderProject\consoleApp1\ConsoleApp1\ConsoleApp1\data\";
		fileName = @"数据-给浙江大学.xls";

		string filePath = folderPath + fileName;

		IWorkbook workBook = new HSSFWorkbook(new FileInputStream(File.OpenRead(filePath)));
		Console.WriteLine("*** read file success");			
		ISheet sheet = workBook.GetSheetAt(0);
		Console.WriteLine("当前sheetName: " + sheet.SheetName);
		Console.WriteLine("当前sheet长度: " + (sheet.LastRowNum + 1));
		// for (int i = 0; i <= sheet.LastRowNum; i++)
		for (int i = 0; i <= 3; i++)
		{
			IRow row = sheet.GetRow(i);
			for (int j = 0; j < row.LastCellNum; j++)
			{
				ICell cell = row.GetCell(j);
				Console.WriteLine(getCellValueToString(cell));
			}
		}
	}

	public void writeExcel(string folderPath, string fileName, IWorkbook workbook)
	{		
		folderPath = @"E:\work_install\riderProject\consoleApp1\ConsoleApp1\ConsoleApp1\data\";
		fileName = @"testWrite.xls";
		IWorkbook wb = new HSSFWorkbook();
		ISheet sheet = wb.CreateSheet("sheet1");
		IRow row = sheet.CreateRow(0);
		row.CreateCell(0).SetCellValue("000");
		row.CreateCell(1).SetCellValue("111");
		row.CreateCell(2).SetCellValue(222);
		try
		{
			FileStream fsWrite = File.OpenWrite(folderPath + fileName);
			wb.Write(fsWrite);
			fsWrite.Close();
		}
		catch (Exception e)
		{
			Console.WriteLine("文件写入错误");
			Console.WriteLine(e.ToString());
		}
	}
	
	

	/**
	 * 读取单个Cell中的值，返回String
	 */
	private string getCellValueToString(ICell cell)
	{
		switch (cell.CellType)
		{
			case CellType.Numeric:
				return cell.NumericCellValue.ToString();
				break;
			case CellType.String:
				return cell.StringCellValue;
			default:
				return "cellValue Error";
		}
	}
    
    
    public string locTest()
    {
        return System.Environment.CurrentDirectory;
    }

    
    
}